package com.itheima.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer_Routing {
    public static void main(String[] args) throws IOException, TimeoutException {
//        1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
//        2.设置参数
        connectionFactory.setHost("192.168.0.104");//默认值为localhost
        connectionFactory.setPort(5672);//默认值为5672
        connectionFactory.setVirtualHost("/itcast");//默认值为/
        connectionFactory.setUsername("heima");
        connectionFactory.setPassword("heima");
//        3.创建连接Connection
        Connection connection = connectionFactory.newConnection();
//        4.创建Channel
        Channel channel =connection.createChannel();
//        5.创建交换机
        /**
         * exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
         * 1.exchange 交换机名称
         * 2.type 交换机类型   :DIRECT("direct")定向, FANOUT("fanout")扇形(广播,发送到每一个与之绑定的队列), TOPIC("topic")通配符的方式, HEADERS("headers")参数匹配;
         * 3.durable 是否持久化
         * 4.autoDelete 是否自动删除
         * 5.internal   是否内部使用
         * 6.arguments  参数
         */
        String exchangeName="test_direct";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,false,null);
//        6.创建队列
        String queueName1="test_direct_queue1";
        String queueName2="test_direct_queue2";
        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);
//        7.绑定交换机和队列
        /**
         * queueBind(String queue, String exchange, String routingKey, Map<String, Object> arguments)
         * 1.queue  队列名称
         * 2.exchange   交换机
         * 3.routingKey 路由键,绑定规则
         *      如果交换机的类型为fanout,routKey设置为空
         *
         */
        //队列1绑定error路由键
        channel.queueBind(queueName1,exchangeName,"error");
        //队列2绑定info,error和warning路由键
        channel.queueBind(queueName2,exchangeName,"info");
        channel.queueBind(queueName2,exchangeName,"error");
        channel.queueBind(queueName2,exchangeName,"warning");
//        8.发送消息
        String body="日志信息:张三调用了findAll方法...日志级别:info...";
        channel.basicPublish(exchangeName,"info",null,body.getBytes());
        channel.close();
        connection.close();

    }
}
